<template>
  <div class="settings-view">
    <div class="settings-header">
      <h1>{{ t('settings.title') }}</h1>
      <p>{{ t('settings.description') }}</p>
    </div>

    <div class="settings-content">
      <!-- 主题设置 -->
      <div class="settings-section theme-card">
        <div class="section-header">
          <h2>
            <el-icon><Sunny /></el-icon>
            {{ t('settings.theme.title') }}
          </h2>
          <p>{{ t('settings.theme.description') }}</p>
        </div>

        <div class="section-content">
          <!-- 主题模式选择 -->
          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.theme.mode') }}</label>
              <span class="setting-desc">{{ t('settings.theme.modeDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-radio-group v-model="themeMode" @change="handleThemeModeChange">
                <el-radio-button value="light">
                  <el-icon><Sunny /></el-icon>
                  {{ t('settings.theme.modeLight') }}
                </el-radio-button>
                <el-radio-button value="dark">
                  <el-icon><Moon /></el-icon>
                  {{ t('settings.theme.modeDark') }}
                </el-radio-button>
                <el-radio-button value="auto">
                  <el-icon><Monitor /></el-icon>
                  {{ t('settings.theme.modeAuto') }}
                </el-radio-button>
                <el-radio-button value="sunrise">
                  <el-icon><Sunny /></el-icon>
                  {{ t('settings.theme.modeSunrise') }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 个性化主题色 -->
          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.theme.color') }}</label>
              <span class="setting-desc">{{ t('settings.theme.colorDesc') }}</span>
            </div>
            <div class="setting-control">
              <div class="theme-colors">
                <div 
                  v-for="theme in themeOptions" 
                  :key="theme.value"
                  class="theme-color-item"
                  :class="{ active: customTheme === theme.value }"
                  @click="handleCustomThemeChange(theme.value)"
                >
                  <div 
                    class="color-preview" 
                    :style="{ backgroundColor: theme.color }"
                  ></div>
                  <span class="color-name">{{ theme.label }}</span>
                </div>
              </div>
            </div>
          </div>


        </div>
      </div>

      <!-- AI助手配置 -->
      <div class="settings-section theme-card">
        <div class="section-header">
          <h2>
            <el-icon><ChatLineRound /></el-icon>
            {{ t('settings.ai.title') }}
          </h2>
          <p>{{ t('settings.ai.description') }}</p>
        </div>

        <div class="section-content">
          <!-- API Key 配置 -->
          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.ai.apiKey') }}</label>
              <span class="setting-desc">{{ t('settings.ai.apiKeyDesc') }}</span>
            </div>
            <div class="setting-control">
              <div class="api-key-input">
                <el-input
                  v-model="apiKeyForm.apiKey"
                  type="password"
                  :placeholder="t('settings.ai.apiKeyPlaceholder')"
                  show-password
                  clearable
                  style="width: 300px;"
                />
                <div class="setting-actions">
                  <el-button
                    type="primary"
                    @click="saveApiKey"
                    :loading="saving"
                    :disabled="!apiKeyForm.apiKey.trim()"
                  >
                    {{ t('settings.ai.save') }}
                  </el-button>
                  <el-button
                    @click="testApiKey"
                    :loading="testing"
                    :disabled="!hasApiKey"
                  >
                    {{ t('settings.ai.test') }}
                  </el-button>
                </div>
              </div>
              <div class="api-key-status" v-if="apiKeyStatus">
                <span class="status-text" :class="apiKeyStatus.type">
                  {{ apiKeyStatus.message }}
                </span>
              </div>
            </div>
          </div>

          <!-- 模型选择 -->
          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.ai.model') }}</label>
              <span class="setting-desc">{{ t('settings.ai.modelDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-select
                v-model="apiKeyForm.model"
                style="width: 300px;"
                :disabled="!hasApiKey"
              >
                <el-option
                  v-for="model in availableModels"
                  :key="model.value"
                  :label="model.label"
                  :value="model.value"
                >
                  <div class="model-option">
                    <span class="model-name">{{ model.label }}</span>
                    <el-tag v-if="model.free" type="success" size="small">免费</el-tag>
                  </div>
                </el-option>
              </el-select>
            </div>
          </div>

          <!-- 获取API Key提示 -->
          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.ai.getApiKey') }}</label>
              <span class="setting-desc">{{ t('settings.ai.getApiKeyDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-button
                type="info"
                @click="openSiliconFlowWebsite"
                text
              >
                前往 硅基流动 官网
                <el-icon><Link /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 其他设置 -->
      <div class="settings-section theme-card">
        <div class="section-header">
          <h2>
            <el-icon><Setting /></el-icon>
            {{ t('settings.other.title') }}
          </h2>
          <p>{{ t('settings.other.description') }}</p>
        </div>

        <div class="section-content">
          <!-- 窗口置顶设置 -->
          <div class="setting-item" v-if="isElectron">
            <div class="setting-label">
              <label>{{ t('settings.other.windowAlwaysOnTop') }}</label>
            </div>
            <div class="setting-control">
              <el-switch
                v-model="windowAlwaysOnTop"
                @change="handleAlwaysOnTopChange"
              />
            </div>
          </div>

          <!-- 关闭到托盘设置 -->
          <div class="setting-item" v-if="isElectron">
            <div class="setting-label">
              <label>{{ t('settings.other.closeToTray') }}</label>
            </div>
            <div class="setting-control">
              <el-switch
                v-model="closeToTray"
                @change="handleCloseToTrayChange"
              />
            </div>
          </div>

          <!-- 最小化到托盘设置 -->
          <div class="setting-item" v-if="isElectron">
            <div class="setting-label">
              <label>{{ t('settings.other.minimizeToTray') }}</label>
            </div>
            <div class="setting-control">
              <el-switch
                v-model="minimizeToTray"
                @change="handleMinimizeToTrayChange"
              />
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.other.language') }}</label>
              <span class="setting-desc">{{ t('settings.other.languageDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-select
                v-model="language"
                :placeholder="t('settings.other.languagePlaceholder')"
                @change="handleLanguageChange"
                style="width: 200px;"
              >
                <el-option label="简体中文" value="zh-CN" />
                <el-option label="English" value="en-US" />
              </el-select>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.other.layout') }}</label>
              <span class="setting-desc">{{ t('settings.other.layoutDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-radio-group v-model="layoutMode" @change="handleLayoutModeChange">
                <el-radio-button value="sidebar">
                  <el-icon><Menu /></el-icon>
                  {{ t('settings.other.layoutSidebar') }}
                </el-radio-button>
                <el-radio-button value="horizontal">
                  <el-icon><Grid /></el-icon>
                  {{ t('settings.other.layoutHorizontal') }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <label>{{ t('settings.other.backgroundEffect') }}</label>
              <span class="setting-desc">{{ t('settings.other.backgroundEffectDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-select
                v-model="backgroundEffect"
                @change="handleBackgroundEffectChange"
                style="width: 200px;"
                :placeholder="t('settings.other.backgroundEffectPlaceholder')"
              >
                <el-option :label="t('settings.other.backgroundEffectNone')" value="none" />
                <el-option :label="t('settings.other.backgroundEffectParticles')" value="particles" />
                <el-option :label="t('settings.other.backgroundEffectBubbles')" value="bubbles" />
                <el-option :label="t('settings.other.backgroundEffectGrid')" value="grid" />
              </el-select>
            </div>
          </div>

          <div class="setting-item" v-if="backgroundEffect !== 'none'">
            <div class="setting-label">
              <label>{{ t('settings.other.backgroundEffectIntensity') }}</label>
              <span class="setting-desc">{{ t('settings.other.backgroundEffectIntensityDesc') }}</span>
            </div>
            <div class="setting-control">
              <el-slider
                v-model="backgroundEffectIntensity"
                :min="10"
                :max="100"
                :step="10"
                @change="handleBackgroundEffectIntensityChange"
                style="width: 200px;"
              />
            </div>
          </div>


        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import {
  Sunny,
  Moon,
  Monitor,
  Setting,
  Menu,
  Grid,
  ChatLineRound,
  Link
} from '@element-plus/icons-vue'
import { useThemeStore, type ThemeMode, type CustomTheme, type Language, type LayoutMode, type BackgroundEffect } from '@/stores/theme'
import { useAIChatStore } from '@/stores/aiChatStore'
import type { ApiKeyConfig } from '@/types/aiChat'

const { t } = useI18n()

// 主题store
const themeStore = useThemeStore()

// AI聊天store
const aiChatStore = useAIChatStore()

// 响应式数据
const themeMode = ref<ThemeMode>(themeStore.themeMode)
const customTheme = ref<CustomTheme>(themeStore.customTheme)
const language = ref<Language>(themeStore.language)
const layoutMode = ref<LayoutMode>(themeStore.layoutMode)
const backgroundEffect = ref<BackgroundEffect>(themeStore.backgroundEffect)
const backgroundEffectIntensity = ref<number>(themeStore.backgroundEffectIntensity)

// AI配置相关数据
const apiKeyForm = ref<ApiKeyConfig>({
  apiKey: '',
  model: 'THUDM/GLM-4.1V-9B-Thinking'
})

// 监听store变化，同步到表单
watch(() => aiChatStore.currentApiKey, (newKey) => {
  if (newKey) {
    apiKeyForm.value.apiKey = newKey
  }
}, { immediate: true })

watch(() => aiChatStore.currentModel, (newModel) => {
  if (newModel) {
    apiKeyForm.value.model = newModel
  }
}, { immediate: true })
const saving = ref(false)
const testing = ref(false)
const apiKeyStatus = ref<{ type: 'success' | 'error' | 'info', message: string } | null>(null)

// 检查是否在Electron环境
const isElectron = computed(() => {
  return (window as any).electronAPI !== undefined
})

// 窗口管理相关数据
const windowAlwaysOnTop = ref(false)
const closeToTray = ref(true)
const minimizeToTray = ref(true)

// AI相关计算属性
const hasApiKey = computed(() => aiChatStore.hasApiKey)
const availableModels = computed(() => [
  {
    value: 'THUDM/GLM-4.1V-9B-Thinking',
    label: 'GLM-4.1V-9B-Thinking',
    description: '智谱AI最新思维模型，支持复杂推理',
    free: true
  },
  {
    value: 'THUDM/GLM-Z1-9B-0414',
    label: 'GLM-Z1-9B-0414',
    description: '智谱AI高效对话模型',
    free: true
  },
  {
    value: 'Qwen/Qwen3-8B',
    label: 'Qwen3-8B',
    description: '阿里云通义千问3代8B模型，性能更强的智能对话',
    free: true
  },
  {
    value: 'deepseek-ai/DeepSeek-R1-0528-Qwen3-8B',
    label: 'DeepSeek-R1-0528-Qwen3-8B',
    description: 'DeepSeek推理模型，基于Qwen3-8B优化的高性能推理引擎',
    free: true
  },
    {
    value: 'tencent/Hunyuan-A13B-Instruct',
    label: 'Hunyuan-A13B',
    description: '腾讯云悍元A13B模型，支持复杂推理',
    free: false
  },
   {
    value: 'moonshotai/Kimi-K2-Instruct',
    label: 'Kimi K2',
    description: 'Kimi K2模型，最强开源模型',
    free: false
  }
])

// 主题选项
const themeOptions = computed(() => [
  { label: t('settings.themeOptions.default'), value: 'default', color: '#0ea5e9' },
  { label: t('settings.themeOptions.blue'), value: 'blue', color: '#3b82f6' },
  { label: t('settings.themeOptions.green'), value: 'green', color: '#22c55e' },
  { label: t('settings.themeOptions.purple'), value: 'purple', color: '#8b5cf6' },
  { label: t('settings.themeOptions.orange'), value: 'orange', color: '#f59e0b' }
] as const)

// 方法
const handleThemeModeChange = (mode: ThemeMode) => {
  themeStore.setThemeMode(mode)
  const modeText = t(`settings.theme.mode${mode.charAt(0).toUpperCase() + mode.slice(1)}` as any)
  ElMessage.success(t('settings.messages.themeModeSuccess', { mode: modeText }))
}

const handleCustomThemeChange = (theme: CustomTheme) => {
  customTheme.value = theme
  themeStore.setCustomTheme(theme)
  const themeName = t(`settings.themeOptions.${theme}` as any)
  // ElMessage.success(t('settings.messages.themeColorSuccess', { themeName }))
}

const handleLanguageChange = (lang: Language) => {
  themeStore.setLanguage(lang)
}

const handleLayoutModeChange = (mode: LayoutMode) => {
  themeStore.setLayoutMode(mode)
}

const handleBackgroundEffectChange = (effect: BackgroundEffect) => {
  themeStore.setBackgroundEffect(effect)
  const effectText = t(`settings.other.backgroundEffect${effect.charAt(0).toUpperCase() + effect.slice(1)}` as any)
  ElMessage.success(t('settings.messages.backgroundEffectSuccess', { effect: effectText }))
}

const handleBackgroundEffectIntensityChange = (intensity: number) => {
  themeStore.setBackgroundEffectIntensity(intensity)
}

// AI配置相关方法
const saveApiKey = async () => {
  if (!apiKeyForm.value.apiKey.trim()) {
    ElMessage.error('请输入API Key')
    return
  }

  saving.value = true
  apiKeyStatus.value = null

  try {
    await aiChatStore.saveApiKey(apiKeyForm.value)
    apiKeyStatus.value = {
      type: 'success',
      message: t('settings.ai.saveSuccess')
    }
    // 保存成功后重新加载配置，显示掩码后的API Key
    await loadApiKeyConfig()
  } catch (error) {
    console.error('Save API key error:', error)
    apiKeyStatus.value = {
      type: 'error',
      message: t('settings.ai.saveFailed')
    }
  } finally {
    saving.value = false
  }
}

const testApiKey = async () => {
  if (!hasApiKey.value) {
    ElMessage.error('请先配置API Key')
    return
  }

  testing.value = true
  apiKeyStatus.value = null

  try {
    const result = await aiChatStore.testApiKey()
    apiKeyStatus.value = {
      type: result.valid ? 'success' : 'error',
      message: result.message
    }
  } catch (error) {
    console.error('Test API key error:', error)
    apiKeyStatus.value = {
      type: 'error',
      message: t('settings.ai.testFailed')
    }
  } finally {
    testing.value = false
  }
}

const openSiliconFlowWebsite = () => {
  window.open('https://cloud.siliconflow.cn/', '_blank')
}

// 窗口管理相关处理函数
const handleAlwaysOnTopChange = async (value: boolean) => {
  if ((window as any).electronAPI) {
    try {
      await (window as any).electronAPI.window.setAlwaysOnTop(value)
      await (window as any).electronAPI.settings.updateWindow({ isAlwaysOnTop: value })
    } catch (error) {
      console.error('设置窗口置顶失败:', error)
      ElMessage.error(t('settings.messages.settingFailed'))
      // 恢复原值
      windowAlwaysOnTop.value = !value
    }
  }
}

const handleCloseToTrayChange = async (value: boolean) => {
  if ((window as any).electronAPI) {
    try {
      await (window as any).electronAPI.settings.updateApp({ closeToTray: value })
    } catch (error) {
      console.error('设置关闭到托盘失败:', error)
      ElMessage.error(t('settings.messages.settingFailed'))
      closeToTray.value = !value
    }
  }
}

const handleMinimizeToTrayChange = async (value: boolean) => {
  if ((window as any).electronAPI) {
    try {
      await (window as any).electronAPI.settings.updateApp({ minimizeToTray: value })
    } catch (error) {
      console.error('设置最小化到托盘失败:', error)
      ElMessage.error(t('settings.messages.settingFailed'))
      minimizeToTray.value = !value
    }
  }
}

const loadApiKeyConfig = async () => {
  try {
    await aiChatStore.loadApiKey()
    // 不需要手动设置，watch会自动同步
  } catch (error) {
    console.error('Load API key config error:', error)
  }
}

// 生命周期
onMounted(async () => {
  // 同步store状态
  themeMode.value = themeStore.themeMode
  customTheme.value = themeStore.customTheme
  language.value = themeStore.language
  layoutMode.value = themeStore.layoutMode
  backgroundEffect.value = themeStore.backgroundEffect
  backgroundEffectIntensity.value = themeStore.backgroundEffectIntensity

  // 加载AI配置
  loadApiKeyConfig()

  // 加载窗口设置（仅在Electron环境）
  if ((window as any).electronAPI) {
    try {
      const windowSettings = await (window as any).electronAPI.settings.getWindow()
      const appSettings = await (window as any).electronAPI.settings.getApp()

      windowAlwaysOnTop.value = windowSettings.isAlwaysOnTop || false
      closeToTray.value = appSettings.closeToTray !== false
      minimizeToTray.value = appSettings.minimizeToTray !== false
    } catch (error) {
      console.error('加载窗口设置失败:', error)
    }
  }
})
</script>

<style lang="scss" scoped>
.settings-view {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.settings-header {
  margin-bottom: 32px;
  
  h1 {
    font-size: 28px;
    font-weight: 600;
    color: var(--text-color-primary);
    margin: 0 0 8px 0;
  }
  
  p {
    font-size: 16px;
    color: var(--text-color-secondary);
    margin: 0;
  }
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.settings-section {
  padding: 24px;
  border-radius: 12px;
  
  .section-header {
    margin-bottom: 24px;
    
    h2 {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 20px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
      
      .el-icon {
        color: var(--theme-primary);
      }
    }
    
    p {
      font-size: 14px;
      color: var(--text-color-secondary);
      margin: 0;
    }
  }
  
  .section-content {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 12px;
  }
  
  .setting-label {
    flex: 1;
    
    label {
      display: block;
      font-size: 16px;
      font-weight: 500;
      color: var(--text-color-primary);
      margin-bottom: 4px;
    }
    
    .setting-desc {
      font-size: 14px;
      color: var(--text-color-secondary);
    }
  }
  
  .setting-control {
    flex-shrink: 0;
    
    @media (max-width: 768px) {
      width: 100%;
    }
  }
}

// AI配置相关样式
.api-key-input {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .setting-actions {
    display: flex;
    gap: 8px;
  }
}

.api-key-status {
  margin-top: 8px;

  .status-text {
    font-size: 14px;

    &.success {
      color: var(--el-color-success);
    }

    &.error {
      color: var(--el-color-error);
    }

    &.info {
      color: var(--el-color-info);
    }
  }
}

.model-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .model-name {
    flex: 1;
  }
}

// 主题色彩选择
.theme-colors {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.theme-color-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  
  &:hover {
    background-color: var(--bg-color-secondary);
  }
  
  &.active {
    border-color: var(--theme-primary);
    background-color: var(--theme-primary-bg);
  }
  
  .color-preview {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 2px solid var(--border-color-light);
  }
  
  .color-name {
    font-size: 12px;
    color: var(--text-color-secondary);
    text-align: center;
  }
}



// 响应式设计
@media (max-width: 768px) {
  .settings-view {
    padding: 16px;
  }
  
  .settings-header {
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
    }
  }
  
  .settings-section {
    padding: 16px;
  }
  
  .theme-colors {
    justify-content: center;
  }
}
</style>
